package com.mgface.thymeleaf.shiro;

import java.time.Instant;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
	private static final Logger log = LoggerFactory.getLogger(HelloWorld.class);

	public static void main(String[] args) throws InterruptedException {
		Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		Subject subject = SecurityUtils.getSubject(); // 在这里subject指的是当前用户
		Session session = subject.getSession(true);// 获得会话
		session.setAttribute("key0", "value");
		log.info(session.getId().toString());
		log.info("当前时间:{},session最后更新时间:{}",Instant.now(),session.getLastAccessTime());
		session.setTimeout(5_000);
		Thread.sleep(4_000);
		session.touch();//修改最后访问时间，让它保持一直不失效，这个对于长时间不操作但是还要保证会话有效作用很大
		log.info("当前时间:{},session最后更新时间:{}",Instant.now(),session.getLastAccessTime());
		log.info("this key0 values is {}", session.getAttribute("key0"));
		if (!subject.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken("javass", "cc");
			token.setRememberMe(true);
			try {
				subject.login(token);
			} catch (UnknownAccountException uae) {
				log.info("There is no user with username of " + token.getPrincipal());
			} catch (IncorrectCredentialsException ice) {
				log.info("Password for account " + token.getPrincipal() + " was incorrect!");
			} catch (LockedAccountException lae) {
				log.info("The account for username " + token.getPrincipal() + " is locked. "
						+ "Please contact your administrator to unlock it.");
			}
		}
		// 打印出subject的标志属性。一般是subject的主要信息之一，例如:用户名，数据库的主键
		log.info("user[{}] is successfully", subject.getPrincipal());

		// 测试subject的角色
		if (subject.hasRole("admin")) {
			log.info("{} have role [{}]", subject.getPrincipal(), "admin");
		} else {
			log.info("没有这个角色");
		}
		//测试subject是否有p3 permission权限
		if(subject.isPermitted("light:1")){
			log.info("有这个light:1权限");
		}else{
			log.info("没有这个light:1权限");
		}
		
		//退出
		subject.logout();
		System.exit(0);
	}

}
